package com.example.order.controller;

import com.example.order.common.CommonResult;
import com.example.order.param.OrderParam;
import com.example.order.service.IOrderService;
import com.example.order.vo.OrderResultVO;
import com.example.product.feign.RemoteProductService;
import com.example.product.feign.param.Price;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.CompletableFuture;

@RestController
public class OrderController {


    @Resource
    private RemoteProductService remoteProductService;

    @Resource
    private IOrderService orderService;

    /**
     * 默认线程池
     */
    @Resource
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    @GetMapping("/test")
    public String test() {
        return remoteProductService.hello();
    }


    @PostMapping("/order")
    public CommonResult<OrderResultVO> order(@RequestBody List<OrderParam> orderParam) {
        return CommonResult.success(orderService.order(orderParam));
    }


    /**
     * 使用线程池模拟并发测试
     *
     * @return {@link String}
     */
    @GetMapping("/test1")
    public String test1() {
        for (int i = 0; i < 10000; i++) {
            CompletableFuture.runAsync(() -> {
                List<OrderParam> orderParams = new ArrayList<>();

                for (int j = 0; j < 2; j++) {
                    Random random = new Random();
                    int productId = random.nextInt(3);
                    while (productId == 0) {
                        productId = random.nextInt(3);
                    }

                    int count = random.nextInt(5);
                    while (count == 0) {
                        count = random.nextInt(5);
                    }
                    OrderParam orderParam = new OrderParam();
                    orderParam.setProductId(productId);
                    orderParam.setCount(count);
                    orderParams.add(orderParam);
                }
                this.order(orderParams);


            }, threadPoolTaskExecutor);
        }
        System.out.println("执行完了");
        return "aa";
    }
}
